package com.hpin.mlxteacher.adapter;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.hpin.mlxteacher.R;
import com.hpin.mlxteacher.bean.AttendanceResult;
import com.hpin.mlxteacher.bean.SimpleResult;
import com.hpin.mlxteacher.child.AttendanceActivity;
import com.hpin.mlxteacher.utils.AbDateUtil;
import com.hpin.mlxteacher.utils.Constant;
import com.hpin.mlxteacher.utils.HttpUtil;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.SimpleBitmapDisplayer;

import java.util.Date;
import java.util.List;

/**
 * Created by Aaron on 15/8/31.
 */
public class AttendanceAdapter extends BaseAdapter {

    private Context ctx;
    private List<AttendanceResult.AttendanceDetail> datas;
    private DisplayImageOptions options;
    //上午还是中午还是下午
    private int type;

    public AttendanceAdapter(Context ctx, List<AttendanceResult.AttendanceDetail> datas, int type) {

        this.ctx = ctx;
        this.datas = datas;
        this.type = type;

        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.icon_default)
                .showImageForEmptyUri(R.drawable.icon_default)
                .showImageOnFail(R.drawable.icon_default)
                .resetViewBeforeLoading(true)
                .cacheOnDisk(true).cacheInMemory(true)
                .cacheOnDisc(true).imageScaleType(ImageScaleType.EXACTLY)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .considerExifParams(true)
                .displayer(new SimpleBitmapDisplayer()).build();

    }

    public void setType(int type) {
        this.type = type;
    }

    @Override
    public int getCount() {
        return datas.size();
    }

    @Override
    public Object getItem(int i) {
        return null;
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    public void setDatas(List<AttendanceResult.AttendanceDetail> attendanceDetails) {
        this.datas = attendanceDetails;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder = null;

        if (convertView == null) {

            convertView = View.inflate(ctx, R.layout.item_receiver, null);
            viewHolder = new ViewHolder();
            viewHolder.iv_receiver_pic = (ImageView) convertView.findViewById(R.id.iv_receiver_pic);
            viewHolder.iv_is_select = (ImageView) convertView.findViewById(R.id.iv_is_select);
            viewHolder.tv_receiver_name = (TextView) convertView.findViewById(R.id.tv_receiver_name);
            convertView.setTag(viewHolder);

        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

//        final ImageView tempIv = viewHolder.iv_is_select;
//        viewHolder.iv_is_select.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                tempIv.setSelected(!tempIv.isSelected());
//            }
//        });
//     LogUtil.e("TAG", "peoples==>" + peoples);
//
//        People people = peoples.get(position);
//
//        LogUtil.e("TAG", "peopel==>" + people);
//
//        Boolean s = people.isSelect;
//        LogUtil.e("TAG", "viewHolder.iv_is_select==>" + viewHolder.iv_is_select);
//        viewHolder.iv_is_select.setSelected(peoples.get(position).isSelect == 1);
//        viewHolder.iv_is_select.setSelected(datas.get(position).isSelect);

        switch (type) {

            case 0://上午

                viewHolder.iv_is_select.setSelected(datas.get(position).signM == 1);

                break;

            case 1://中午

                viewHolder.iv_is_select.setSelected(datas.get(position).signA == 1);

                break;

            case 2://下午

                viewHolder.iv_is_select.setSelected(datas.get(position).signN == 1);

                break;

        }

        //学生姓名
        viewHolder.tv_receiver_name.setText(datas.get(position).nickName);
        //头像
        ImageLoader.getInstance().displayImage(datas.get(position).picUrl, viewHolder.iv_receiver_pic, options);


        final ImageView iv_select = viewHolder.iv_is_select;
        //点击签到
        viewHolder.iv_receiver_pic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

//                if (iv_select.isSelected()) //如果已经签到
//                    return;

                //更改签到状态
                changeSignStatus(datas.get(position).id, datas.get(position).nickName, position, iv_select.isSelected());
//                changeSignStatus(datas.get(position).stuId, datas.get(position).stuName, position, iv_select.isSelected());

            }
        });


        return convertView;
    }

    /**
     * 更改学生的签到状态
     *
     * @param stuId    学生姓名
     * @param stuName  学生id
     * @param position 点击的签到的学生的position
     * @param selected 是否已经签到过
     */
    private void changeSignStatus(final String stuId, String stuName, final int position, final boolean selected) {

        //TODO 提示语更改
        new AlertDialog.Builder(ctx).setCancelable(true).setTitle("更改签到状态").setMessage(stuName).setNegativeButton("取消", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

                dialogInterface.dismiss();

            }
        }).setPositiveButton(selected ? "取消签到" : "添加签到", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

                dialogInterface.dismiss();
                //签到
                sign(stuId, position, selected);
            }
        }).show();


    }

    /**
     * 签到 更改签到状态
     *
     * @param stuId
     * @param position
     * @param selected 是否已经签到过
     */
    private void sign(String stuId, final int position, final boolean selected) {

        SharedPreferences sp = ctx.getSharedPreferences(Constant.CONFIG, ctx.MODE_PRIVATE);


        JSONObject j = new JSONObject();
        j.put("token", sp.getString(Constant.token, ""));
        j.put("id", stuId);
        j.put("day", AbDateUtil.getStringByFormat(new Date(), AbDateUtil.dateFormatYMD));
        j.put("check", selected ? "0" : "1");
        j.put("time", type);

//        SignInBean signInBean = new SignInBean();
//
//        signInBean.token = sp.getString(Constant.token, "");
//        signInBean.id = stuId;
//        signInBean.day = AbDateUtil.getStringByFormat(new Date(), AbDateUtil.dateFormatYMD);
//        signInBean.check = selected ? "0" : "1";
//        signInBean.time = type + "";//0是早上,1是中午,2是晚上

        HttpUtil.setPostRequest("签到中...", ctx, Constant.WEB_ROOT + Constant.CHECKDAY,
               j.toJSONString(), null, new HttpUtil.SuccessListener() {
                    @Override
                    public void setOnSuccessListener(String str) {

                        try {

                            SimpleResult result = JSONObject.parseObject(str, SimpleResult.class);

                            if (result.code == Constant.SUCCESS) {

                                switch (type) { //判断当前是哪个时间段, 修改签到状态

                                    case 0:
                                        datas.get(position).signM = selected ? 0 : 1;
                                        break;
                                    case 1:
                                        datas.get(position).signA = selected ? 0 : 1;
                                        break;
                                    case 2:
                                        datas.get(position).signN = selected ? 0 : 1;
                                        break;

                                }

                                notifyDataSetChanged();

                                if (ctx instanceof AttendanceActivity) {

                                    AttendanceActivity att = (AttendanceActivity) ctx;
                                    if (selected) {
                                        //TODO 判断是签到 还是 取消签到
                                        //签到个数+1
                                        att.removeSignPeople();
                                    } else {
                                        //签到个数-1
                                        att.addSignPeople();

                                    }
                                }
                            } else {
                                Toast.makeText(ctx, Constant.showErrorMsg(result.code, ctx), Toast.LENGTH_SHORT).show();
                            }

                        } catch (Exception e) {

                            e.printStackTrace();
                            Toast.makeText(ctx, "签到失败", Toast.LENGTH_SHORT).show();

                        }

                    }
                }, null);

    }

    private class ViewHolder {
        private ImageView iv_receiver_pic;
        private ImageView iv_is_select;
        private TextView tv_receiver_name;

    }

}
